<!--
- File:    商品详细页
-->
<template>
  <div>
    <div class="Web_Box">
      <!--<div style="position: fixed; z-index: 2;width: 100%">-->
      <!--<i class="TransparentBut TransparentReturn iconfont icon-leftdot" @click="back"></i>-->
      <!--<router-link :to="{name: 'cart-list'}">-->
      <!--<i class="TransparentBut TransparentList iconfont icon-shoppingcart"></i>-->
      <!--</router-link>-->
      <!--<i class="TransparentBut TransparentCollection iconfont icon-collection" :class="{'collected': goodsCommonInfo.fav_state == 1}" @click="switchCollect"></i>-->
      <!--</div>-->
      <div class="detail_head f-cb" style="z-index: 2"><i class="iconfont icon-back fl" @click="back"></i>
        <div class="detail_tab">
          <ul>
            <li class="mr10">
              <a href="javascript:void(0)" :class="{'on': currentPosition == 'normal'}" @click="scrollToTop">商品</a></li>
            <li><a href="javascript:void(0)" :class="{'on': currentPosition == 'detail'}" @click="scrollToDetail">详情</a>
            </li>
          </ul>
        </div>
        <i class="iconfont icon-xin fr" :class="{'collected': goodsCommonInfo.fav_state == 1}" @click="switchCollect"></i>
      </div>
      <div class="CommodityDetails hidden" style="margin-top: 38px">
        <mt-swipe :auto="0" class="swiper-container bg_fff" style="height: 16rem">
          <mt-swipe-item class="swiper-slide" v-for="(item,index) in goodsCommonInfo.showimage" :key="index">
            <div class="swiper-slide">
              <img class="swipe-img" style="width: 100%" :src="$config.imgsite + $config.goodsImgSrc + storeId + '/' + item + '_w640'" alt=""/>
            </div>
          </mt-swipe-item>
        </mt-swipe>
        <!--活动-->
        <div class="active_box" v-if="goodsCommonInfo.groupbuy_info">
          <div class="active_cont f-cb">
            <div class="text">
              <p class="slh w5rem">{{goodsCommonInfo.groupbuy_info.groupbuy_name}}</p>
              <p class="f12" v-if="goodsCommonInfo.groupbuy_info.upper_limit > 0">仅限购{{goodsCommonInfo.groupbuy_info.upper_limit}}件</p>
            </div>
            <div class="disib vm daojishi fr " v-if="goodsCommonInfo.groupbuy_info.type == 1">
              <p class="f12 pb5">距结束仅剩</p>
              <span class="timem disib vm">{{timeRemain.days}}</span><span class=" disib vm">&nbsp;天&nbsp;</span><span class="timem disib vm">{{timeRemain.hours}}</span><span class=" disib vm">&nbsp;时&nbsp;</span><span class="timem disib vm">{{timeRemain.minutes}}</span><span class="disib vm">&nbsp;分&nbsp;</span><span class="timem disib vm">{{timeRemain.seconds}}</span><span class="disib vm">&nbsp;秒&nbsp;</span>
            </div>
          </div>
        </div>
        <!--活动 end-->
        <!--商品基础信息Start-->
        <div class="BasicInfo">
          <h1>{{goodsCommonInfo.goods_name}}</h1>
          <div class="f-cb pr20 pl20" v-if="buyType != $dictionary.buyType.integral">
            <p class="Price">
              <!--<i class="iconfont icon-zhe"></i>-->
              <span style="color: red">￥{{goodsCommonInfo.goods_price_range}}</span>
              <span style="font-size: 14px; color: #898989;text-decoration: line-through;margin-left: 0.25rem" v-show="goodsCommonInfo.goods_price_range && goodsCommonInfo.goods_price_range.toString().indexOf('-') == -1">￥{{goodsCommonInfo.goods_marketprice}}</span>
            </p>
            <!--<p class="primary"><i class="iconfont icon-yuan"></i><span>￥{{goodsCommonInfo.goods_marketprice_range}}</span></p>-->
            <a href="javascript:void(0)" class="Rent_btn" @click="switchBuyType($dictionary.buyType.buy)" v-show="buyType == $dictionary.buyType.rent && goodsCommonInfo.relative_commonid">购买此花</a>
            <a href="javascript:void(0)" class="Rent_btn" @click="switchBuyType($dictionary.buyType.rent)" v-show="buyType == $dictionary.buyType.buy && goodsCommonInfo.relative_commonid">租摆此花</a>
          </div>
          <div v-else>
            <div class="f-cb pr20 pl20">
              <p class="Price">
                <span class="jifen">{{goodsCommonInfo.goods_price_range}}</span><span class="inte">积分</span></p>
            </div>
            <div class="test">您当前有<span class="cr_f23030">{{goodsCommonInfo.integral}}</span>积分
              <span v-if="goodsCommonInfo.need_goods_price == -1">，若积分不足，可用金额抵扣</span>
              <span v-if="goodsCommonInfo.need_goods_price > 0">，再支付<span class=" cr_f23030">{{goodsCommonInfo.need_goods_price | toFixed(2)}}</span>元可兑换</span>
            </div>
          </div>
        </div>
        <!--商品基础信息End-->
        <p class="tisb" v-show="goodsCommonInfo.is_voucher == '0'">此商品不可用优惠券</p>
        <!--<p class="Freight"><span class="cr_595757">运费：中国大陆地区包邮；港澳台，及境外请联系客服</span></p>-->
        <div class="Ency f-cb" v-show="telLink || qqLink">
          <a :href="telLink" v-show="telLink">
            <i class="iconfont icon-dianhua" style="color: #999"></i>
            <span>电话</span>
          </a>
          <!--<a href="mqqwpa://im/chat?chat_type=wpa&uin=382473286&version=1&src_type=web&web_src=bjhuli.com">-->
            <!--<i class="iconfont icon-QQ" style="color: #999"></i><span>QQ</span></a>-->
          <a :href="qqLink" v-show="qqLink">
            <i class="iconfont icon-QQ" style="color: #999"></i><span>QQ</span></a>
        </div>
        <!--优惠券-->
        <div class="d_coupon f-cb" @click="switchCouponShow(true)" v-show="buyType != $dictionary.buyType.integral && couponList.requested && couponList.data.length > 0">
          <i class="iconfont icon-youhuiquan"></i>领取优惠券<i class="iconfont icon-more fr"></i></div>
        <!--优惠券-->
        <!--产品参数-->
        <div class="d_coupon f-cb" style="color:#333;" @click="switchGoodsParamShow(true)">产品参数<i class="iconfont icon-more fr"></i>
        </div>
        <!--产品参数-->
        <div class="Ency f-cb" v-show="goodsCommonInfo.m_id != 0">
          <a href="javascript:void(0)" @click="gotoWiki(goodsCommonInfo.m_id, '2')"><i class="iconfont icon-gerenhuli"></i><span>养护知识</span></a><a href="javascript:void(0)" @click="gotoRelationList(goodsCommonInfo.m_id)"><i class="iconfont icon-baike"></i><span>花友互动</span></a>
        </div>
        <!--商品评价Start-->
        <div class="CommodityEvaluation mt20 bor_b_dcdddd">
          <div class="tit">
            <h2>商品评价 ({{goodsCommentCount}})</h2>
            <div class="data disn">好评率<span class="cr_ff5c36">100%</span></div>
          </div>
          <div class="CommentList" v-show="goodsComment.data.length > 0">
            <ul>
              <li v-for="item in goodsComment.data" v-show="item.geval_state == 1 || item.geval_frommemberid == memberInfo.member_id">
                <div class="user">
                  <div class="pic">
                    <img :src="$config.imgsite + $config.avatarSrc + item.member_avatar + '_w150'" alt=""/></div>
                  <span>{{item.member_name}}</span></div>
                <p class="text">{{item.geval_content}}</p>
                <p class="date">{{item.geval_addtime}}</p>
              </li>
            </ul>
            <div class="more" @click="gotoCommentList">查看更多评价</div>
            <!--<div v-show="goodsComment.allLoaded" style="text-align: center;padding: 0.5rem">没有更多评价了~</div>-->
          </div>
        </div>
        <!--商品评价End-->
        <!--上拉Start-->
        <div class="DetailsEntry">图文详情</div>
        <!--上拉End-->
        <!--商品详情Start-->
        <div>
          <div id="goodsDetail" class="goods-detail" ref="detail" v-html="goodsCommonInfo.bodys" v-show="goodsCommonInfo.bodys!=''">

          </div>
          <div style="padding: 0.5rem 0;text-align: center" v-show="goodsCommonInfo.bodys==''">
            暂时没有详情介绍
          </div>
        </div>
        <!--商品详情End-->

      </div>
    </div>
    <div class="PurchaseOperation gd ">
      <a href="" class="shopno disn">此商品已售罄</a>
      <template v-if="buyType != $dictionary.buyType.integral">
        <div class="left fl">
          <ul>
            <li class="bor-r-eee" @click="gotoHome"><i class="iconfont icon-app-index-a"></i> <span>首页</span></li>
            <li @click="gotoCart"><i class="iconfont icon-gouwuche"></i> <span>购物车</span></li>
          </ul>
        </div>
        <button type="button" class="but bg_221814" @click="buyClick(0)">加入购物车</button>
        <button type="button" class="but bg_3dbb6e" @click="buyClick(1)" v-if="buyType != $dictionary.buyType.rent">立即购买</button>
        <button type="button" class="but bg_3dbb6e" @click="buyClick(1)" v-else>租花</button>
      </template>
      <template v-else>
        <button type="button" class="but bg_3dbb6e" style="width: 100%" @click="buyClick(1)">立即兑换</button>
      </template>
    </div>
    <!--弹窗-->
    <div v-if="addToCartModelShow">
      <div class="PopBg" @click="switchAddToCartModelShow(false)"></div>
      <!--选择商品属性弹窗Start-->
      <div class="AttributeSelectionPop " id="AttributeSelectionPop" style="z-index: 99">
        <div class="BasicInfo"><i class="iconfont icon-close" @click="switchAddToCartModelShow(false)"></i>
          <div style="border: none">
            <img class="pic" :src="$config.imgsite + $config.goodsImgSrc + storeId + '/' + goodsInfo.goods_image + '_w150'" alt=""/>
          </div>
          <p class="Price fl" v-if="buyType != $dictionary.buyType.integral">￥{{goodsInfo.goods_price | discount(goodsCommonInfo.groupbuy_rebate)}}</p>
          <div v-else>
            <p class="Price fl">{{parseInt(goodsInfo.goods_price)}}积分</p>
            <div class="test" style="clear: both; padding: .25rem 0;">您当前有<span class="cr_f23030">{{goodsInfo.integral}}</span>积分
              <span v-if="integralMoney">，再支付<span class=" cr_f23030">{{integralMoney | toFixed(2)}}</span>元可兑换</span>
            </div>
          </div>
          <p class="Stock c">库存<span class="ml20">{{goodsInfo.goods_storage}}</span></p>
        </div>
        <div style="max-height:12rem;overflow:auto;">
          <div class="AttributeList" v-for="(attributeClassify, classifyIndex) in goodsAttribute.attri_list">
            <h3>{{attributeClassify.name}}</h3>
            <ul>
              <li v-for="attribute in attributeClassify.list" :class="{'on': selectedAttributeIdList[classifyIndex] == attribute.id}" @click="selectAttributeClick(attribute.id, classifyIndex)" style="width: auto; padding: 0 0.25rem">{{attribute.name}}
              </li>
            </ul>
          </div>
        </div>
        <div class="Number">
          <h3>数量 <span class="Purchase"></span><span class="Purchase" v-if="goodsCommonInfo.groupbuy_info && goodsCommonInfo.groupbuy_info.upper_limit > 0">(限购{{goodsCommonInfo.groupbuy_info.upper_limit}}件)</span>
          </h3>
          <div class="QuantityControl">
            <i class="iconfont icon-jian1" :class="{'no': buyNum <= 1}" @click="reduceNum"></i>
            <input type="tel" v-model="buyNum" @blur="handleNumChange">
            <i class="iconfont icon-jia1" :class="{'no': buyNum >= this.goodsInfo.goods_storage || (goodsCommonInfo.groupbuy_info && buyNum >= parseInt(goodsCommonInfo.groupbuy_info.upper_limit))}" @click="addNum"></i>
          </div>
        </div>
        <div class="OperationButton f-cb">
          <button type="button" :class="{'bg_3dbb6e': this.goodsInfo.goods_storage > 0, 'bg_d3d2d2': this.goodsInfo.goods_storage <= 0}" style="width: 100%" @click="buyConfirm">确定</button>
        </div>
      </div>
    </div>
    <!--选择商品属性弹窗End-->
    <!--优惠券-->
    <div class="coupbg" v-if="goodsParamModelShow">
      <div class="coupon_box">
        <h3>产品参数</h3>
        <div class="cp_parameter" style="max-height:18rem;overflow:auto;">
          <p class="texts" v-for="param in goodsCommonInfo.tags" v-show="param.value"><span class="tname">{{param.key}}</span>{{param.value}}
          </p>
          <p style="text-align: center; margin-top: 4rem" v-show="goodsCommonInfo.tags.length <= 0">当前没有参数信息</p>
          <div class="c_btn" @click="switchGoodsParamShow(false)">关闭</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {Swipe, SwipeItem} from 'mint-ui'
  import {mapModules, mapRules} from 'vuet'
  import couponPop from '../../components/couponPop'
  export default{
    beforeRouteEnter (to, from, next) {
      next(vm => {
        vm.from = from.name
        vm.toFullPath = to.fullPath
      })
    },
    mixins: [
      mapModules({memberInfo: 'memberInfo', couponSetting: 'couponSetting'}),
      mapRules({once: ['memberInfo', 'couponSetting']})
    ],
    data() {
      return {
        storeId: this.$route.query.storeId || this.$utils.getQueryString('storeId'),
        storeInfo: {tel: '', qq: ''},
        buyType: this.$route.query.buyType || this.$utils.getQueryString('buyType') || this.$dictionary.buyType.buy,
        from: null,
        toFullPath: null,
        currentPosition: 'normal',
        goodsCommonid: this.$route.params.id,
        goodsCommonInfo: {}, // 商品通用信息
        goodsInfo: {}, // 具体规格的商品信息
        newGoodsInfo: {}, // 新品
        goodsAttribute: {}, // 商品规格
        goodsComment: {requested: false, loading: false, allLoaded: false, page: 1, pageSize: 10, data: []},
        goodsCommentCount: 0,
        addToCartModelShow: false,
        couponModelShow: false,
        newGoodsNoticeModelShow: false,
        goodsParamModelShow: false,
        selectedAttributeIdList: [],
        buyNum: 1,
        buyActionType: 0, // 购买操作类型：0加入购物车，1直接购买
        timeRemain: {days: 0, hours: 0, minutes: 0, seconds: 0},
        countdownInterval: null,
        couponList: {requested: false, data: []}
      }
    },
    components: {
      'mtSwipe': Swipe,
      'mtSwipeItem': SwipeItem
    },
    mounted() {
      this.getGoodsCommonInfo(this.goodsCommonid)
      this.getGoodsComment(this.goodsCommonid, 1, 1)
      this.getCouponList()
    },
    beforeDestroy() {
      clearInterval(this.countdownInterval)
    },
    computed: {
      telLink() {
        let result = ''
        if (this.storeInfo.tel) {
          result = 'tel: ' + this.storeInfo.tel
        }
        return result
      },
      qqLink() { // http://shang.qq.com/v3/widget.html->推广工具（qq号要申请后才可以调起）
        let result = ''
        let deviceType = this.$utils.getDeviceType()
        if (this.storeInfo.qq) {
          if (deviceType == 'wx-Android' || deviceType == 'wx-iPhone') {
            result = 'http://wpa.qq.com/msgrd?v=1&uin=' + this.storeInfo.qq
          } else {
            result = 'mqqwpa://im/chat?chat_type=wpa&uin=' + this.storeInfo.qq + '&version=1&src_type=web&web_src=bjhuli.com'
          }
        }
        return result
      },
      integralMoney() {
        if (this.buyType != this.$dictionary.buyType.integral) {
          return ''
        }
        if (this.buyNum == '' || this.buyNum == 0) {
          return ''
        }
        if (!this.goodsCommonInfo.integral || !this.goodsInfo.goods_price) {
          return ''
        }
        let integralMoney = ''
        let memberIntegralNum = this.goodsCommonInfo.integral
        let needIntegralCount = this.buyNum * this.goodsInfo.goods_price
        if (parseInt(needIntegralCount) > parseInt(memberIntegralNum)) {
          integralMoney = (needIntegralCount - memberIntegralNum) * this.couponSetting.points_money
        }
        return integralMoney
      }
    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      $route () {
        this.init()
      }
    },
    methods: {
      back() {
        if (this.from) {
          this.$router.go(-1)
        } else {
//          this.$router.push({name: 'home', query: {storeId: this.storeId}})
          window.location.href = 'http://' + window.location.host + '/wap/?storeId=' + this.storeId // ios微信分享要如此跳转后才能正确分享
        }
      },
      switchGoodsParamShow(boolValue) {
        if (boolValue) {
          this.$utils.addBodyFix() // 显示模态框，防止滚动模态框里的div时body也滚动
        } else {
          this.$utils.removeBodyFix()
        }
        this.goodsParamModelShow = boolValue
      },
      switchCouponShow(boolValue) {
        couponPop({storeId: this.storeId})
      },
      gotoCart() {
        this.$router.push({name: 'cart-list'})
      },
      gotoHome() {
//        this.$router.push({name: 'home', query: {storeId: this.storeId}})
        window.location.href = 'http://' + window.location.host + '/wap/?storeId=' + this.storeId // ios微信分享要如此跳转后才能正确分享
      },
      gotoWiki(mid, type) {
        this.$router.push({name: 'wiki', query: {id: mid, type: type}})
      },
      gotoRelationList(mid) {
        this.$router.push({name: 'relation-list', params: {mid: mid}})
      },
      switchBuyType(type) {
        this.$router.push({
          name: 'goods-detail',
          params: {id: this.goodsCommonInfo.relative_commonid},
          query: {storeId: this.storeId, buyType: type}
        })
      },
      init() {
        this.initData()
        this.getGoodsCommonInfo(this.goodsCommonid)
        this.getGoodsComment(this.goodsCommonid, 1, 1)
      },
      initData() {
        this.storeId = this.$route.query.storeId
        this.buyType = this.$route.query.buyType || this.$dictionary.buyType.buy
        this.from = null
        this.toFullPath = null
        this.currentPosition = 'normal'
        this.goodsCommonid = this.$route.params.id
        this.goodsCommonInfo = {}
        this.newGoodsInfo = {} // 新品
        this.goodsAttribute = {} // 商品规格
        this.goodsComment = {requested: false, loading: false, allLoaded: false, page: 1, pageSize: 10, data: []}
        this.addToCartModelShow = false
        this.newGoodsNoticeModelShow = false
        this.selectedAttributeIdList = []
        this.buyNum = 1
        this.buyActionType = 0 // 购买操作类型：0加入购物车，1直接购买
        this.timeRemain = {days: 0, hours: 0, minutes: 0, seconds: 0}
        this.countdownInterval = null
      },
      getCouponList() {
        this.$request.getStoreCouponList(this.storeId).then(data => {
          this.couponList.data = data
        }).finally(() => {
          this.couponList.requested = true
        })
      },
      handleNumChange() {
        console.log('blur..')
        if (this.buyNum == '' || this.buyNum == 0) {
          this.buyNum = 1
          return
        }
        if (parseInt(this.buyNum) > parseInt(this.goodsInfo.goods_storage)) {
          this.buyNum = this.goodsInfo.goods_storage
        }
      },
      lisentScroll() {
        window.addEventListener('scroll', this.$utils.throttle2(this.switchPositionTag, 200))
      },
      switchPositionTag() {
        if (!this.$refs.detail) {
          return
        }
        if (document.body.scrollTop < 200) {
          this.currentPosition = 'normal'
          return
        }
        var top = this.$refs.detail.getBoundingClientRect().top // 元素顶端到可见区域顶端的距离
        var se = document.documentElement.clientHeight // 浏览器可见区域高度。
        if (top <= se) { // 50为底部栏高度
          this.currentPosition = 'detail'
        } else {
          this.currentPosition = 'normal'
        }
      },
      scrollToTop() {
        window.scrollTo(1, 1)
        this.currentPosition = 'normal'
      },
      scrollToDetail() {
        window.scrollTo(1, this.$refs.detail.offsetTop - 50)
        this.currentPosition = 'detail'
      },
      handleSwipeChange(index) {
        let imgSwipeList = document.getElementsByClassName('swipe-img')
        let swiperContainer = document.getElementsByClassName('swiper-container')[0]
        this.$utils.imgLoaded(imgSwipeList[index].src).then(img => { // 图片加载完成后改变轮播容器的高度
          swiperContainer.style.cssText = 'height: ' + img.height / img.width * document.documentElement.clientWidth + 'px'
        }).catch(e => {
          console.error('商品轮播图' + index + '加载失败')
        })
      },
      getGoodsCommonInfo(id) {
        this.$request.getGoodsCommonInfo(id).then(data => {
          this.goodsCommonInfo = data
          this.getGoodsAttributeList(this.goodsCommonid)
//          if (data.showimage && data.showimage.length > 0) { // 有商品轮播图
//            let url = this.$config.imgsite + this.$config.goodsImgSrc + data.showimage[0] + '_gdw640'
//            this.$utils.imgLoaded(url).then(img => { // 图片加载完成后改变轮播容器的高度
//              let swiperContainer = document.getElementsByClassName('swiper-container')[0]
//              swiperContainer.style.cssText = 'height: ' + img.height / img.width * document.documentElement.clientWidth + 'px'
// //              console.log('imgWH', img.width, img.height)
//            }).catch(e => {
//              console.error('商品轮播图加载失败')
//            })
//          }
          if (data.groupbuy_info) {
            this.getTimeRemain(data.groupbuy_info.end_time)
            clearInterval(this.countdownInterval)
            this.countdownInterval = setInterval(() => {
              this.getTimeRemain(data.groupbuy_info.end_time)
            }, 1000)
          }
          let title = data.goods_name
          if (data.groupbuy_info && data.groupbuy_info.groupbuy_name) {
            title = data.groupbuy_info.groupbuy_name
          }
          let imgSrc = this.$config.imgsite + this.$config.goodsImgSrc + this.storeId + '/' + data.goods_image
//          console.log('微信自己添加的参数', this.$utils.getQueryString('from'), this.$utils.getQueryString('isappinstalled'))
//          console.log('share2', window.location.href, title, imgSrc)
          console.log('img', imgSrc)
          this.$native.weixinShare(window.location.href, title, imgSrc)
        }).catch(e => {
          this.$toast('获取商品详情失败:' + e.msg)
        }).finally(() => {
          setTimeout(() => {
            this.lisentScroll()
          }, 200)
        })
      },
      getGoodsComment(id, page, pageSize) {
        this.goodsComment.loading = true
        this.$request.getGoodsCommentList(id, page, pageSize).then(data => {
          if (this.$utils.isEmptyObject(data)) {
            return
          }
          if (data.data.length < this.goodsComment.pageSize) {
            this.goodsComment.allLoaded = true
          }
          this.goodsCommentCount = data.count
          this.goodsComment.data = [...this.goodsComment, ...data.data]
        }).finally(() => {
          this.goodsComment.requested = true
          this.goodsComment.loading = false
        })
      },
      getGoodsAttributeList(id) {
        this.$request.getGoodsAttributeList(id).then(data => { // 不传规格数组，返回商品规格列表
          this.goodsAttribute = data
          for (let i = 0; i < data.goods_info.goods_spec.length; i++) {
            this.selectedAttributeIdList[i] = data.goods_info.goods_spec[i].id
          }
          this.goodsInfo = data.goods_info
        })
      },
      async selectAttributeClick(id, index) {
        this.$set(this.selectedAttributeIdList, index, id)
        try {
          let data = await this.$request.getGoodsAttributeList(this.goodsCommonInfo.goods_commonid, this.selectedAttributeIdList) // 传规格数组，返回具体商品
          this.goodsInfo = data.goods_info
        } catch (e) {
          this.$toast('选择规格失败:' + e.msg)
        }
      },
      gotoCommentList() {
        this.$router.push({
          name: 'comment-list',
          params: {id: this.goodsCommonid},
          query: {commonid: this.goodsCommonid}
        })
      },
      switchCollect() {
        if (this.goodsCommonInfo.fav_state == 0) { // 未收藏过
          this.addCollect()
        } else {
          this.delCollect()
        }
      },
      addCollect() {
        this.$request.addCollect(this.goodsCommonInfo.goods_commonid).then(data => {
          this.$toast('添加收藏成功')
          this.goodsCommonInfo.fav_state = 1
        }).catch(e => {
          this.$toast('添加收藏失败:' + e.msg)
        })
      },
      delCollect() {
        this.$request.delCollect(this.goodsCommonInfo.goods_commonid).then(data => {
          this.$toast('取消收藏成功')
          this.goodsCommonInfo.fav_state = 0
        }).catch(e => {
          this.$toast('取消收藏失败:' + e.msg)
        })
      },
      addNum() {
        if (this.buyNum >= parseInt(this.goodsInfo.goods_storage)) {
          this.$toast('超过商品库存数量了~')
          return
        }
        if (this.goodsCommonInfo.groupbuy_info && this.buyNum >= parseInt(this.goodsCommonInfo.groupbuy_info.upper_limit)) {
          this.$toast('超过限购数量了~')
          return
        }
        this.buyNum++
      },
      reduceNum() {
        if (this.buyNum <= 1) {
          return
        }
        this.buyNum--
      },
      getGoodsInfoByAttr() {
        return new Promise((resolve, reject) => {
          for (let i = 0; i < this.goodsAttribute.attri_list.length; i++) {
            if (!this.selectedAttributeIdList[i]) {
              reject({msg: '请选择 ' + this.goodsAttribute.attri_list[i].name})
            }
          }
          this.$request.getGoodsAttributeList(this.goodsCommonInfo.goods_commonid, this.selectedAttributeIdList).then(data => {
            if (!data.goods_info.goods_id) {
              reject({msg: '该规格商品不存在'})
            }
            resolve(data.goods_info)
          }).catch(e => {
            reject({msg: '获取该规格商品失败'})
          })
        })
      },
      buyClick(buyActionType) {
        this.buyActionType = buyActionType
        this.switchAddToCartModelShow(true)
      },
      async buyConfirm() {
        try {
          let cartType = this.$dictionary.cartType.buy // 默认买花
          if (this.buyType == this.$dictionary.buyType.rent) {
            cartType = this.$dictionary.cartType.rent // 租花
          }
          let goodsInfo = await this.getGoodsInfoByAttr()
          let cartId = await this.$request.addGoodsToCart(goodsInfo.goods_id, this.buyNum, cartType)
          if (goodsInfo.goods_storage < this.buyNum) {
            this.$toast('当前库存不足, 请注意购买数量')
            return
          }
          if (this.buyActionType === 0) { // 只是加入购物车
            this.switchAddToCartModelShow(false)
            this.$toast('加入购物车成功')
          } else if (this.buyActionType === 1) { // 立即购买：加入购物车-> 订单确认页
            this.switchAddToCartModelShow(false)
            if (this.buyType == this.$dictionary.buyType.buy || this.buyType == this.$dictionary.buyType.integral) { // 购
              this.$router.push({name: 'order-confirm', query: {cart: cartId, buyType: this.buyType}})
            } else if (this.buyType == this.$dictionary.buyType.rent) { // 租
              this.$router.push({name: 'order-rent-confirm', query: {cart: cartId, buyType: this.buyType}})
            }
          }
        } catch (e) {
          console.error('加入购物车失败', e)
          this.$toast('加入购物车失败:' + e.msg)
        }
      },
      switchAddToCartModelShow(boolValue) {
        if (boolValue) {
          this.$utils.addBodyFix() // 显示模态框，防止滚动模态框里的div时body也滚动
        } else {
          this.$utils.removeBodyFix()
        }
        this.addToCartModelShow = boolValue
      },
      switchNewGoodsNoticeModelShow(boolValue) {
        this.newGoodsNoticeModelShow = boolValue
      },
      // 去除iframe字符串的宽高
      resetIframWH(html) {
        html = html.replace(/height=\d+/g, '')
        html = html.replace(/width=\d+/g, 'width="100%"')
        return html
      },
      getTimeRemain(endTimeTamp) {
        if (endTimeTamp) {
          let currentTime = new Date()
          let endTime = new Date()
          endTime.setTime(endTimeTamp * 1000)
          this.timeRemain = this.$utils.timeDif(currentTime, endTime)
        }
      }
    }
  }
</script>

<style lang="less">
  .DetailsEntry:before {
    content: none;
  }

  .bg_d3d2d2 {
    background-color: #d3d2d2;
  }

  .collected {
    color: #45a73a !important;
  }

  .goods-detail {
    img {
      width: 100% !important;
      height: auto !important;
    }
  }
</style>
